package com.rongke.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.model.PropName;
import com.rongke.model.PropValue;
import com.rongke.model.Sku;
import com.rongke.model.SkuPage;
import com.rongke.service.PropNameService;
import com.rongke.service.PropValueService;
import com.rongke.service.SkuService;
import com.rongke.utils.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @version : Ver 1.0
 * @SkuController
 * @商品skuController
 */
@RestController
@RequestMapping(value = "/api/sku")
@Transactional
@CrossOrigin(origins = "*", maxAge = 3600)
public class SkuController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private SkuService skuService;
    @Autowired
    private PropNameService propNameService;
    @Autowired
    private PropValueService propValueService;

    /**
     * @param sku
     * @return 返回值JsonResp
     * @添加商品sku
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addSku(@RequestBody Sku sku) {
        log.debug("添加商品sku");
        sku.setGmtDatetime(new Date());
        skuService.insert(sku);
        return JsonResp.ok(sku);
    }

    /**
     * @param skuList
     * @return 返回值JsonResp
     * @批量添加商品sku
     */
    @RequestMapping(value = "/addSkuBatch", method = RequestMethod.POST)
    public JsonResp addSkuBatch(@RequestBody List<Sku> skuList) {
        log.debug("批量添加商品sku");
        if (skuList.size() == 0)
            return JsonResp.toFail("server:添加的多规格为空！");
        for (int i = 0; i < skuList.size(); i++) {
            skuList.get(i).setGmtDatetime(new Date());
        }
        skuService.insertBatch(skuList);
        return JsonResp.ok(skuList);
    }

    /**
     * @param sku
     * @return 返回值JsonResp
     * @修改商品sku
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateSku(@RequestBody Sku sku) {
        log.debug("修改商品sku");
        sku.setUptDatetime(new Date());
        skuService.updateById(sku);
        return JsonResp.ok(sku);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @根据id查找商品sku
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectSku(Long id) {
        log.debug("查找商品sku");
        Sku sku = skuService.selectById(id);
        return JsonResp.ok(sku);
    }

    /**
     * @param sku
     * @return 返回值JsonResp
     * @根据条件查找商品sku
     */
    @RequestMapping(value = "/selectByCondition", method = RequestMethod.POST)
    public JsonResp selectSkuByCondition(@RequestBody Sku sku) {
        log.debug("根据条件查找商品sku");
        if (sku == null)
            return JsonResp.toFail("参数不能为空");
        List<Sku> skuList = skuService.selectByCondition(sku);
        return JsonResp.ok(skuList);
    }

    /**
     * @param propMap
     * @return
     * @后台添加一组规格
     */
    @RequestMapping(value = "/addProp", method = RequestMethod.POST)
    public JsonResp addProp(@RequestBody Map<String, Object> propMap) {
        log.debug("后台添加一组规格");
        String classifyId = propMap.get("classifyId").toString();
        String propName = propMap.get("prop_name").toString();
        if (StringUtil.isEmpty(classifyId) || StringUtil.isEmpty(propName))
            return JsonResp.toFail("必须有具体分类和属性名称参数！");
        ArrayList<String> propValueList = (ArrayList<String>) propMap.get("prop_value");
        PropName propNameObj = new PropName();
        propNameObj.setAttrName(propName);
        propNameObj.setClassifyId(Long.valueOf(classifyId));
        propNameService.insert(propNameObj);
        Long pId = propNameObj.getId();
        List<PropValue> pvList = new ArrayList<>();
        for (String propValue : propValueList) {
            PropValue pv = new PropValue();
            pv.setPropNameId(pId);
            pv.setPropValue(propValue);
            pv.setGmtDatetime(new Date());
            pvList.add(pv);
        }
        propValueService.insertBatch(pvList);
        Map<String, Object> pvMap = new HashMap<>();
        pvMap.put("propName", propNameObj);
        pvMap.put("propValueList", pvList);
        return JsonResp.ok(pvMap);
    }

    /**
     * @param propId
     * @return
     * @根据规格名称id删除一个规格名和一组规格值
     */
    @RequestMapping(value = "/delProp", method = RequestMethod.GET)
    public JsonResp delProp(Long propId) {
        log.debug("根据规格名称id删除一个规格名和一组规格值");
        EntityWrapper<PropValue> ew = new EntityWrapper<>();
        ew.eq("prop_name_id", propId);
        propValueService.delete(ew);
        propNameService.deleteById(propId);
        return JsonResp.ok("删除成功！");
    }

    /**
     * @param sku
     * @return
     * @添加统一规格商品sku
     */
    @RequestMapping(value = "/addUniSku", method = RequestMethod.POST)
    public JsonResp addUniSku(@RequestBody Sku sku) {
        log.debug("添加统一规格商品sku");
        sku.setGmtDatetime(new Date());
        skuService.insert(sku);
        return JsonResp.ok(sku);
    }

    /**
     * @return
     * @根据具体分类id查找规格集合
     */
    @RequestMapping(value = "/selectSpecListByClassifyId", method = RequestMethod.GET)
    public JsonResp selectSpecListByClassifyId(String classifyId) {
        log.debug("根据具体分类id查找规格集合");
        if (StringUtil.isEmpty(classifyId))
            return JsonResp.toFail("参数不能为空！");
        int cid = Integer.valueOf(classifyId);
        List<PropName> propNameList = propNameService.selectSpecListByClassifyId(cid);
        return JsonResp.ok(propNameList);
    }

    /**
     * @param goodsId
     * @return 返回值JsonResp
     * @根据商品id获取规格信息
     */
    @RequestMapping(value = "/selectPropList", method = RequestMethod.GET)
    public JsonResp selectPropList(Long goodsId) {
        log.debug("根据商品id获取规格信息");
        EntityWrapper<Sku> ew = new EntityWrapper<>();
        ew.eq("goods_id", goodsId);
        List<Sku> skuList = skuService.selectList(ew);
        if (!skuList.isEmpty()) {
            if (skuList.get(0).getIfUniformSpec() == 0) {
                Map skuListMap = new HashMap();
                skuListMap.put("skuList", skuList);
                return JsonResp.ok(skuListMap);
            }
        }
        String[] pvstrArr=skuList.get(0).getPropStr().split(",");
        Integer propCount=pvstrArr.length;
        //获取属性名id的list，按序
        List<String> pIds = new ArrayList<>();
        for (int i = 0; i < propCount; i++) {
            pIds.add(pvstrArr[i].split("-")[0]);
        }
        //按序创建属性值id的list，一个属性名id对应一个属性值list（多个属性值id）
        List<List<String>> pvList=new ArrayList<>();
        for(int i=0;i<propCount;i++){
            pvList.add(new ArrayList<>());
        }
        //按位添加属性值ids，如每个sku的第一个 p-v 中的v结合构成pvList的第一项，即第一个属性名对应的多个属性值
        skuList.forEach(e->{
            String[] propArr=e.getPropStr().split(",");
            for(int j=0;j<propCount;j++){
                String vId=propArr[j].substring(propArr[j].indexOf("-")+1);
                pvList.get(j).add(vId);
            }
        });
        List<PropName> propNameLists = new ArrayList<>();
        //按位拼合valueList（属性值集合）到prop（属性名）的propValues中
        for(int i=0;i<propCount;i++){
            PropName pn=propNameService.selectById(pIds.get(i));
            EntityWrapper<PropValue> ewv=new EntityWrapper<>();
            ewv.in("id",pvList.get(i));
            List<PropValue> pvs=propValueService.selectList(ewv);
            pn.setPropValues(pvs);
            propNameLists.add(pn);
        }
/*         int i = 0, y = skuList.size();
        Sku sku = null;
        String propStr[] = null;
        List<String> values = new ArrayList<>();
        List<Map> skuMapList = new ArrayList<>();
        propStr = skuList.get(0).getPropStr().split(",");
        for (String str : propStr) {
            values.add(str.split("-")[0]);
        }
        //该商品所含规格值Set
        Set vIdSet=new HashSet();
        for(Sku sk:skuList){
            String[] propArr=sk.getPropStr().split(",");

            for (String str : propArr) {
                String aa=str.substring(str.indexOf("-")+1);
                vIdSet.add(Long.valueOf(str.split("-")[1]));
            }
        }
       for (; i < y; i++) {
            sku = skuList.get(i);
            Map map = new HashMap();
            map.put("id", sku.getId());
            map.put("goodsId", sku.getGoodsId());
            map.put("price", sku.getPrice());
            map.put("propStr", sku.getPropStr());
            map.put("skuUrl", sku.getSkuUrl());
            map.put("nums", sku.getNums());
            map.put("ifUniformSpec", sku.getIfUniformSpec());
            map.put("state", sku.getState());
            map.put("inventory", sku.getInventory());
            skuMapList.add(map);
        }*/
/*        List<PropValue> propList = null;
        List<PropName> propNames = new ArrayList<>();
        if (!values.isEmpty()) {
            Map map = new HashMap();
            map.put("values", values);
            propList = propValueService.selectPropValueList(map);
            for (PropValue pv : propList) {
                int m = 0, n = propNames.size();
                if (!propNames.isEmpty()) {
                    for (; m < n; m++) {
                        PropName propN = propNames.get(m);
                        if (StringUtil.isNotEmpty(pv.getPropName().getAttrName()) && pv.getPropName().getAttrName().equals(propN.getAttrName())) {
                            List<PropValue> pv1 = propN.getPropValues();
                            PropValue propValue = new PropValue();
                            propValue.setId(pv.getId());
                            propValue.setPropValue(pv.getPropValue());
                            if(vIdSet.contains(propValue.getId())){
                                pv1.add(propValue);
                            }
                            break;
                        }
                    }
                }
                if (propNames.isEmpty() || m == n) {
                    List<PropValue> pv1 = new ArrayList<>();
                    PropName pn1 = pv.getPropName();
                    PropValue propValue = new PropValue();
                    propValue.setId(pv.getId());
                    propValue.setPropValue(pv.getPropValue());
                    if(vIdSet.contains(propValue.getId())){
                        pv1.add(propValue);
                    }
                    pn1.setPropValues(pv1);
                    propNames.add(pn1);
                }

            }
        }

        //存放排好顺序的规格信息(按propStr 以逗号分隔后的prop_name_id 顺序排序)
        List<PropName> propNameList = new ArrayList<>();
        //对规格信息排序
        for (int m2 = 0, n2 = values.size(); m2 < n2; m2++) {
            for (int m = 0, n = propNames.size(); m < n; m++) {
                PropName pn = propNames.get(m);
                if (String.valueOf(pn.getId()).equals(values.get(m2))) {
                    propNameList.add(pn);
                    break;
                }
            }
        }*/
        //整理 返回map
        Map skuListMap = new HashMap();
//        skuListMap.put("skuList", skuMapList);
//        skuListMap.put("propNameList", propNameList);
        skuListMap.put("skuList", skuList);
        skuListMap.put("propNameList", propNameLists);

        return JsonResp.ok(skuListMap);
    }


    /**
     * 更新属性值拼接名
     *
     * @return
     */
    @RequestMapping(value = "/uptValuesStr", method = RequestMethod.GET)
    public JsonResp uptValuesStr() {
        log.debug("更新属性值拼接名");
        EntityWrapper<Sku> ew = new EntityWrapper<>();
        ew.eq("if_uniform_spec", 1);
        ew.isNull("values_str");
        List<Sku> skuList = skuService.selectList(ew);
        List<Sku> sList = new ArrayList<>();
        for (Sku temp : skuList) {
            Sku s = new Sku();
            s.setId(temp.getId());
            String valuesStr = "";
            String propStr = temp.getPropStr();
            String[] propArr = propStr.split(",");
            for (String str : propArr) {
                String[] pArr = str.split("-");
                Long v_id = Long.valueOf(pArr[1]);
                PropValue pv = propValueService.selectById(v_id);
                if (null != pv)
                    valuesStr += "、" + pv.getPropValue();
            }
            if (valuesStr.length() > 0) {
                valuesStr = valuesStr.substring(1);
                s.setValuesStr(valuesStr);
                sList.add(s);
            }
        }
        skuService.updateBatchById(sList);
        return JsonResp.ok(sList);
    }

    /**
     * 获取sku列表，包含商品信息
     *
     * @param skuPage
     * @return
     */
    @RequestMapping(value = "/getSkuListAdmin", method = RequestMethod.POST)
    public JsonResp getSkuListAdmin(@RequestBody SkuPage skuPage) {
        log.debug("获取sku列表，包含商品信息");
        Page page = skuPage.getPage();
        Sku sku = skuPage.getSku();
        Map map = new HashMap();
        Map conditionMap = new HashMap();
        conditionMap = page.getCondition();
        String ifUniformSpec = conditionMap.get("ifUniformSpec").toString();
        Integer startIndex = (page.getCurrent() - 1) * page.getSize();
        map.put("startIndex", startIndex);
        map.put("size", page.getSize());
        //产品线筛选
        if (null != skuPage.getIntParam()) {
            map.put("goodsType", skuPage.getIntParam());
        }
        //库存筛选
        if (null != skuPage.getLzInventory()) {
            map.put("lzInventory", skuPage.getLzInventory());
        }
        //是否统一规格筛选
        if (StringUtil.isNotEmpty(ifUniformSpec)) {
            map.put("ifUniformSpec", ifUniformSpec);
        }
        //搜索
        if (null != skuPage.getSearchText()) {
            map.put("goodsName", skuPage.getSearchText());
        }

        //传具体商品id去修改规格
        if(null!=skuPage.getLongParam()){
            map.put("goodsId",skuPage.getLongParam());
        }
        List<Sku> skuList = skuService.getSkuListAdmin(map);
        Integer total = skuService.getSkuListCountAdmin(map);
        page.setRecords(skuList);
        page.setTotal(total);
        return JsonResp.ok(page);
    }

}




